package org.microframework.cloud.gateway.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 降级处理控制器
 * 处理服务调用超时或异常情况
 */
@Slf4j
@RestController
public class FallbackController {

    /**
     * 熔断降级处理
     */
    @RequestMapping("/fallback")
    public Mono<Map<String, Object>> fallback(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        String serviceId = getServiceId(path);
        
        log.error("服务[{}]调用失败，请求路径: {}", serviceId, path);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.SERVICE_UNAVAILABLE.value());
        response.put("message", String.format("服务[%s]不可用，请稍后再试", serviceId));
        response.put("path", path);
        response.put("success", false);
        
        return Mono.just(response);
    }
    
    /**
     * 从请求路径中提取服务ID
     */
    private String getServiceId(String path) {
        if (path == null || path.isEmpty()) {
            return "unknown";
        }
        
        // 解析路径中的服务ID，例如 /system/user -> system
        String[] parts = path.split("/");
        if (parts.length > 1) {
            return parts[1];
        }
        
        return "unknown";
    }
} 